import {utils} from "../utils/utils";
import {GameMode, GameVar, GlobalObject} from "../game/GameVar";
import {COMMON_CID} from "../web/model/UserModel";
import {model} from "../web/model/Model";
import {wxUtils} from "../wx/wxUtils";
import {StatEvent, Statistic} from "../../statistic/statistic";
import {WordsUtils} from "../utils/wordsUtils";
import RankLayer from "./ranklayer";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Menu extends cc.Component {

  @property(cc.Label)
  labelCoin: cc.Label = null;

  @property(cc.Label)
  labelDiamond: cc.Label = null;

  @property(cc.Sprite)
  openDataContext: cc.Sprite = null;

  // @property(cc.Node)
  // rotateNode: cc.Node = null;

  @property(cc.Label)
  txtName: cc.Label = null;

  @property(cc.Sprite)
  headImg: cc.Sprite = null;

  @property(cc.Prefab)
  sevendayPrefab: cc.Prefab = null;
  @property(cc.Prefab)
  settingPrefab: cc.Prefab = null;
  @property(cc.Prefab)
  newbiePrefab: cc.Prefab = null;
  @property(cc.Prefab)
  dailyPrefab: cc.Prefab = null;
  @property(cc.Prefab)
  everydaySignPrefab = null;
  @property(cc.Prefab)
  guidePrefab = null
  @property(cc.Prefab)
  invitePrefab = null
  @property(RankLayer)
  rankLayer:RankLayer = null;

  private wxClubBtn = null;
  private requestGroupRank = false;
  private wxOnShow: Function = null;
  private texture: cc.Texture2D = new cc.Texture2D()

  async onLoad() {
    wxUtils.setShareInfo();
    cc.director.preloadScene('game');

    wxUtils.postMessage({cmd: 'enterMenu'})
    //显示排行榜
    wxUtils.postMessage({cmd: 'showRankFriendTop'});
    this.setWXShowFunc();
    this.coinChange();
    this.diamondChange();
    // this.setNewbieButton();
    // this.setSignButton();
    // this.createClubButton();
    // model.user.on('newbieGift', this.setNewbieButton, this);
    model.user.on(COMMON_CID.COIN + '', this.coinChange, this);
    model.user.on(COMMON_CID.DIAMOND + '', this.diamondChange, this);

    //显示头像和昵称
    wxUtils.getHeadTexture(this.headImg);
    this.txtName.string = GameVar.userInfo.nick;
    wxUtils.showMenuAd();
    // this.swimIcon.node.active = false;
    // cc.loader.loadRes(`icon/${model.user.activeSwim}`, (err, res) => {
    //   this.swimIcon.spriteFrame = new cc.SpriteFrame(res);
    //   this.swimIcon.node.active = true;
    // });
  }

  onLimitTimeTouch() {
    GameVar.mode = GameMode.LIMITED;
    GlobalObject.voiceSource.playSwitch();
    Statistic.emit(StatEvent.BTN_LIMIT)
    cc.director.loadScene('game');
  }

  onInfiTouch() {
    GameVar.mode = GameMode.INFINITY;
    Statistic.emit(StatEvent.BTN_INFI)
    GlobalObject.voiceSource.playSwitch();
    cc.director.loadScene('game');
  }

  onShopTouch() {
    Statistic.emit(StatEvent.BTN_SHOP)
    GlobalObject.voiceSource.playClick();
    cc.director.loadScene('shop')
  }

  private setWXShowFunc() {
    if (this.wxOnShow) {
      return;
    }
    this.wxOnShow = (resp) => {
      if (resp && resp.shareTicket && this.requestGroupRank) {
        wxUtils.postMessage({cmd: 'showRankGroup', shareTicket: resp.shareTicket});
        cc.director.loadScene('rankgroup');
      }
    };
    wxUtils.onShow(this.wxOnShow);
  }

  private coinChange() {
    if (model.user.itemsMap[COMMON_CID.COIN]) {
      this.labelCoin.string = model.user.itemsMap[COMMON_CID.COIN].num.toString()
    } else {
      this.labelCoin.string = '0'
    }
  }

  private diamondChange() {
    if (model.user.itemsMap[COMMON_CID.DIAMOND]) {
      this.labelDiamond.string = model.user.itemsMap[COMMON_CID.DIAMOND].num.toString()
    } else {
      this.labelCoin.string = '0'
    }
  }

  private createClubButton() {
    this.wxClubBtn && this.wxClubBtn.destroy();
    let size = cc.view.getFrameSize();
    this.wxClubBtn = wxUtils.createGameClubButton({
      icon: 'white',
      style: {
        left: size.width - 40,
        top: 50,
        width: 30,
        height: 30
      }
    });
  }

  showRankLayer() {
    Statistic.emit(StatEvent.BTN_RANK)
    this.rankLayer.show();
  }

  async showRankGroup() {
    Statistic.emit(StatEvent.GROUP_RANK_CLICK)
    let resp = await wxUtils.shareToFriends();
    if (!resp) {
      WordsUtils.warn('查看失败，发送到群从群中点击查看');
    } else {
      this.requestGroupRank = true;
    }
  }

  showSign() {
    Statistic.emit(StatEvent.BTN_SEVEN)
    let prefab = model.user.sevenLoginValid ? this.sevendayPrefab : this.everydaySignPrefab;
    cc.instantiate(prefab).parent = cc.director.getScene();
    setTimeout(() => {
      wxUtils.hideMenuAd()
    })
  }

  // setNewbieButton(event?: cc.Event.EventCustom) {
  //   // 新手礼包领取后变为分享
  //   let imgLingQu = this.btnGift.getChildByName('img_lingQu');
  //   let label = this.btnGift.getChildByName('Label').getComponent(cc.Label);
  //   !event && this.shakeAction(imgLingQu);
  //   imgLingQu.active = model.user.newbieGiftValid;
  //   !model.user.newbieGiftValid && (label.string = '分    享');
  // }

  // setSignButton() {
  //   let label = this.btnSevenLogin.getChildByName('Label').getComponent(cc.Label);
  //   label.string = model.user.sevenLoginValid ? '七日好礼' : '每日签到';
  // }

  showNewbieGift() {
    wxUtils.hideMenuAd()
    if (model.user.newbieGiftValid) {
      Statistic.emit(StatEvent.BTN_NEWBIE)
      cc.instantiate(this.newbiePrefab).parent = cc.director.getScene();
    } else {
      wxUtils.shareToFriends();
    }
  }

  showShare() {
    wxUtils.shareToFriends()
  }

  showSetting() {
    wxUtils.hideMenuAd()
    cc.instantiate(this.settingPrefab).parent = cc.director.getScene();
  }

  onDestroy() {
    wxUtils.hideMenuAd();
    wxUtils.offShow(this.wxOnShow);
    this.wxClubBtn && this.wxClubBtn.destroy();
    // model.user.off('newbieGift', this.setNewbieButton, this);
    model.user.off(COMMON_CID.COIN + '', this.coinChange, this)
    model.user.off(COMMON_CID.DIAMOND + '', this.diamondChange, this)
  }

  update(dt) {
    this.texture.initWithElement(wxUtils.getSharedCanvas());
    this.texture.handleLoadedTexture();
    this.openDataContext.spriteFrame = new cc.SpriteFrame(this.texture)
  }

  private shakeAction(node: cc.Node) {
    let shake = () => {
      let onceTime = 0.05;
      let seq = cc.sequence(
        cc.rotateTo(onceTime, -10),
        cc.rotateTo(onceTime * 2, 10),
        cc.rotateTo(onceTime * 2, -10),
        cc.rotateTo(onceTime * 2, 10),
        cc.rotateTo(onceTime, 0),
        cc.delayTime(Math.random() * 2 + 1),
        cc.callFunc(shake)
      );
      node.runAction(seq);
    };
    shake();
  }

  private scaleAction() {
    const duration = 1;
    return cc.sequence(
      cc.scaleTo(duration * 0.3, 1.10, .85),
      cc.scaleTo(duration * 0.1, .85, 1.10),
      cc.scaleTo(duration * 0.1, 1.10, .85),
      cc.scaleTo(duration * 0.15, .95, 1.05),
      cc.scaleTo(duration * 0.1, 1.05, .95),
      cc.scaleTo(duration * 0.25, 1, 1),
      cc.delayTime(4)
    ).repeatForever();
  }

  start() {
    GlobalObject.voiceSource.playMenuBgm();
    // this.rotateNode.runAction(this.scaleAction());
  }

  onBoxTouch() {
    wxUtils.hideMenuAd()
    // GlobalObject.tips.show('敬请期待');
    Statistic.emit(StatEvent.BTN_BOX)
    cc.instantiate(this.dailyPrefab).parent = cc.director.getScene();
  }

  showLucky() {
    Statistic.emit(StatEvent.LUCKY_CLICK)
    cc.director.loadScene('lucky')
  }

  showInvite() {
    wxUtils.hideMenuAd()
    cc.instantiate(this.invitePrefab).parent = cc.director.getScene()
  }

  showAchievement() {
    cc.director.loadScene('achievement', () => {
    })
    wxUtils.hideMenuAd()
    Statistic.emit(StatEvent.GRADE_CLICK)
  }

  showMoreGame() {
    wxUtils.toSdk()
  }

  friendsCombat() {
    WordsUtils.warn('该功能暂未开放')
  }

  openBoard(way: number) {
    switch (way) {
      case 0:
        break;
      case 1:
        this.showNewbieGift();
        break;
      case 2:
        this.showSign()
        break;
      case 3:
        this.onBoxTouch();
        break;
      case 4:
        break;
      case 5:
        break;
    }
  }

  showGuide() {
    cc.instantiate(this.guidePrefab).parent = cc.director.getScene();
  }
}
